var map, //高德地图对象
    bus,loadData,dbClick,carMove,
    trackReplay;

require(['gaodeMap', 'jquery-ui', 'file1', 'file2', 'grid', 'date'], function () {
    var $trajBeginTime = $("#trajBeginTime"),
        corpId,
        lineId,
        carId,
        carforOverspeedDetail,
        tempNode,
        tmpStartPot,
        stationMarkers = [],
        stmarker, endmarker, polyLine,
        flag=false;
    var $slider = $("#slider");//进度条

    //左侧树单击事件
    commonFun.leftTreeNodeClickObj['carAnaCarTrack'] = carAnaCarTrack;

    function carAnaCarTrack(event, treeId, treeNode) {
        if (treeNode.type === "CAR") {
            carId = treeNode.id;
            initData();
            if (tmpStartPot) {
                map.setMapCenterAndLevel(tmpStartPot.lng, tmpStartPot.lat, 14);
            }
            tempNode = treeNode.getParentNode();
            if (map && map.map) {
                if (stationMarkers.length) {
                    stationMarkers = [];
                }
            }
            drawLine(tempNode);
        }
    }
    /* commonFun.leftTreeNodeClickObj['carAnaCarTrack'] = function (event, treeId, treeNode) {

     };*/

    function loadCorpAndLine() {
        $.ajaxExt({
            url: "/operationManage/getCorpAndLine.htm",
            data: {"carId": carId}
        }).done(function (result) {
            corpId = result.corpId;
            lineId = result.lineId;
        });
    }

    //绘制线路
    function loadLine(city, lineName, lineId) {
        var ar = lineName.split('[');
        lineName = ar[0];
        AMap.service(["AMap.LineSearch"], function () {
            var linesearch = new AMap.LineSearch({
                pageIndex: 1,
                city: city,
                pageSize: 1,
                extensions: 'all'
            });
            linesearch.search(lineName, function (status, result) {
                if (status === 'complete' && result.info === 'OK') {
                    var lineNum = result.lineInfo.length;
                    if (lineNum) {
                        var lineArr = result.lineInfo;
                        var pathArr = lineArr[0].path;
                        var stops = lineArr[0].via_stops;
                        var startPot = stops[0].location;
                        var endPot = stops[stops.length - 1].location;
                        tmpStartPot = startPot;
                        if (!map) {
                            map = new MapGaoDe(startPot.lng, startPot.lat, 14);
                        }
                        var stationsLen = lineArr[0].via_stops.length;
                        for (var i = 0; i < stationsLen; i++) {
                            stationMarkers.push(new AMap.Marker({
                                map: map.map,
                                position: lineArr[0].via_stops[i].location,
                                offset: new AMap.Pixel(-3, -3),
                                icon: $.getProjectName() + "/component/map/images/way_btn2.png",
                                title: lineArr[0].via_stops[i].name,
                                zIndex: 13
                            }));
                        }
                        drawbusLine(startPot, endPot, pathArr);
                    }
                } else {
                    $.messager.alert('提示', '未找到对应的线路');
                }
            });
        });
    }

    //绘制路线
    function drawbusLine(startPot, endPot, BusArr) {
        //绘制起点，终点
        stmarker = new AMap.Marker({
            map: map.map,
            position: [startPot.lng, startPot.lat], //基点位置
            icon: $.getProjectName() + "/component/map/images/start_flag.png",
            zIndex: 13
        });
        endmarker = new AMap.Marker({
            map: map.map,
            position: [endPot.lng, endPot.lat], //基点位置
            icon: $.getProjectName() + "/component/map/images/end_flag.png",
            zIndex: 13
        });
        //绘制乘车的路线
        polyLine = new AMap.Polyline({
            map: map.map,
            path: BusArr,
            strokeColor: "#52BE17",//线颜色
            strokeWeight: 5//线宽
        });
        map.map.setFitView();
    }

    function drawLine(parentNode) {
        if (parentNode.type === "LINE") {
            if (parentNode.province == '北京' || parentNode.province == '上海' ||
                parentNode.province == '天津' || parentNode.province == '重庆') {
                loadLine(parentNode.province, parentNode.name, parentNode.id);
            } else {
                loadLine(parentNode.city, parentNode.name, parentNode.id);
            }
        }
    }

    loadData = function (carId, beginTime, endTime,name,province,city) {
        $("#djtable").grid("clearGridData");
        $.ajaxExt({
            loadMask:{msg:'数据加载中'},
            url: "/operationManage/getDriveTrajInfo.htm?carId=" + carId + "&beginTime=" + beginTime + "&endTime=" + endTime
        }).done(function (data) {
            initData();
            if (!data) {
                $.messager.alert("提示", "没有轨迹数据", "info");
                $("#djtable").grid("clearGridData");
            } else {
                $slider.slider("enable");
                $("#djtable").grid('setGridParam', {data: data}).trigger("reloadGrid");
                map.setMapCenterAndLevel(data[0].loLgt, data[0].loLtt, 14);
                if(name!=""){
                    tempNode={};
                    tempNode.name = name;
                    tempNode.province = province;
                    tempNode.city = city;
                    carforOverspeedDetail=carId;
                }
                drawLine(tempNode);
                bus = new Bus(map, data[0].licPltNo, data[0].loLgt, data[0].loLtt);
                bus.show();
                trackReplay = new TrackReplay(map, bus, data);
                trackReplay.isKeepCenter = true;
                if (!trackReplay.onPlayIndexChange) {
                    trackReplay.onPlayIndexChange = function (playIndex, totalIndex) {
                        if (data && data[playIndex] && data[playIndex].rcrdTime) {
                            $("#djtable").grid('setSelection', data[playIndex].rcrdTime); // 选中grid中的对应行
                            if (trackReplay.state != "pause") {
                                $slider.slider("option", "value", playIndex);
                                $slider.slider("option", "max", totalIndex - 1);
                            }
                        }
                    };
                }
                if (!trackReplay.onTrackReplayComplete) {
                    trackReplay.onTrackReplayComplete = function () {
                        if (trackReplay.state != "pause") {
                            $('#play').removeClass('pause');
                            trackReplay.stopReplay();
                            $slider.slider("disable");
                        }
                    };
                }
                if (corpId != "" && lineId != "") {
                    //上下行
                    $.ajaxExt({
                        url: "/lineTrackRel/getLineTrackRelUp.htm?organId=" + "" + "&corpId=" + corpId + "&lineId=" + lineId
                    }).done(function (data) {
                        if (data) {
                            if (data.length > 0) {
                                var lineArr = new Array(); // 将坐标点数组转化成高德地图可用的数组对象
                                for (var i = 0; i < data.length; i++) { // 画线数组赋值
                                    lineArr.push(new AMap.LngLat(data[i].loLgt, data[i].loLtt));
                                }
                                map.drawRunTrack(lineArr);
                                map.mapFitView();
                            }
                        }
                    });
                    $.ajaxExt({
                        url: "/lineTrackRel/getLineTrackRelDown.htm?organId=" + "" + "&corpId=" + corpId + "&lineId=" + lineId
                    }).done(function (data) {
                        if (data) {
                            if (data.length > 0) {
                                var lineArr = new Array(); // 将坐标点数组转化成高德地图可用的数组对象
                                for (var i = 0; i < data.length; i++) { // 画线数组赋值
                                    lineArr.push(new AMap.LngLat(data[i].loLgt, data[i].loLtt));
                                }
                                map.drawRunTrack(lineArr);
                                map.mapFitView();
                            }
                        }
                    });
                }
            }

        });
    }

    var initData = function () {
        $('#play').removeClass('pause');
        $slider.slider("option", "value", 0).slider("disable");
        if (trackReplay) {
            trackReplay.stopReplay();
        }
        map && map.clear();
    };

    //初始化
    (function () {
        var $iCenter = $('#iCenter').css('height', $(window).height());

        function sliderChange(event, ui) {
            if (ui.value) {
                carMove(ui.value);
            }
        }

        //function carMove(index) {
        //    if (trackReplay && trackReplay.playIndex != index) {
        //        trackReplay.setBusIndex(index, true);
        //    }
        //}

        $slider.slider({
            max: 200,
            min: 0,
            step: 1,
            value: 100,
            orientation: "horizontal",
            range: "min",
            slide: sliderChange//,
            //change: sliderChange
        });

        $slider.slider("value", 100);

        $("#djtable").grid({
            datatype: "local",
            colModel: [
                {name: 'rcrdId', label: 'rcrdId', hidden:true},
                {name: 'licPltNo', label: '车牌号', width: 220},
                {name: 'rcrdTime', label: '时间', width: 220},
                {name: 'upDn', label: '方向', width: 150},
                {name: 'detailAdr', label: '详细地址', width: 300},
                {name: 'spdOfMotVhi', label: '速度', width: 300},
                {name: 'mftTypeName', label: '故障名称', width: 150},
                {name: 'drvSctBhv', label: '异常行为', width: 150}
            ],
            height: 180,
            width: $(window).width() - 2,
            showPager: false,
            ondblClickRow: function (rowid, iRow, iCol, e) { // 双击行触发的事件
                var playIndex = iRow - 1; // 对应滑块位置数据(0,1,2...)
                $slider.slider("option", "value", playIndex);
                carMove(playIndex);
                flag=true;
                $('#play').click();
            },
            multiselect: false
        });


        //播放、暂停按钮事件
        $('#play').on('click', function () {
            var $t = $(this);
            if (!trackReplay) {
                return;
            }
            if(flag){
                $t.addClass('pause');
            }

            if ($(this).hasClass('pause')) {//暂停转播放
                $t.removeClass('pause');
                trackReplay.pauseReplay();
                $slider.slider("disable");
            } else {//播放转暂停
                $t.addClass('pause');
                trackReplay.startReplay(60);
                $slider.slider("enable");
            }
            flag=false;
        });

        //停止按钮事件
        $('#stop').on('click', function () {
            if (!trackReplay) {
                return;
            }
            $('#play').removeClass('pause');
            if (trackReplay) {
                trackReplay.stopReplay();
            }
            $slider.slider("option", "value", 0).slider("disable");
        });

        //快退事件
        $('#back').on('click', function () {
            if (!trackReplay) {
                return;
            }
            var value = $slider.slider("option", "value");

            if (value - 1 >= 0) {
                $slider.slider("option", "value", value - 1);
                carMove(value - 1);
            }
        });

        //快进事件
        $('#forward').on('click', function () {
            if (!trackReplay) {
                return;
            }
            var value = $slider.slider("option", "value");

            if ($slider.slider("option", "max") >= value + 1) {
                $slider.slider("option", "value", value + 1);
                carMove(value + 1);
            }
        });

        $(window).on('resize', function () {
            var up = $('#updown').hasClass('slide-btn-active');
            $iCenter.height(up ? $(window).height() - 2 : $(window).height() - 180);
            $("#djtable").grid('setGridWidth', $(window).width() - 2);
        });

        $('#updown').on('click', function () {
            var up = $(this).hasClass('slide-btn-active');
            $('#bottom')[up ? 'show' : 'hide']();
            $iCenter.height(up ? $(window).height() - 180 : $(window).height() - 2);
            $(this).closest('.control-panel').css('bottom', up ? 180 : 0);
            $(this).toggleClass('slide-btn-active');
        });
    })();

    //查询
    $('#trajSearchBnt').on("click", function () {
        //时间
        var beginTime, lastingTime, endTime;
        beginTime = $trajBeginTime.val();
        lastingTime = $("#lastingTime").val();
        endTime = beginTime.substr(0, 14) + lastingTime + ":00";
        if(!carId){
            carId=carforOverspeedDetail;
        }
        if (carId) {
            loadCorpAndLine();
            if (beginTime && beginTime != "") {
                loadData(carId, beginTime, endTime,"","","");
                var faultType = "",unSafeBeh="";
                $.ajaxExt({
                    url: "/operationManage/getAllRealTimeFailure2.htm",
                    data: {'carId': carId, 'beginTime': beginTime, 'endTime': endTime}
                }).done(function (data) {

                    $(data).each(function (i, item) {
                        faultType += "<tr ondblclick = dbClick('"+item.rcrdId+"')><td width='46%' class='al pl10'>" + item.mftTypeName + "</td><td>" + item.rcrdTime + "</td></tr>";
                    });
                    $("#faultType").html(faultType);
                });
                $.ajaxExt({
                    url: "/operationManage/getDrivingBehaviorList2.htm",
                    data: {'carId': carId, 'beginTime': beginTime, 'endTime': endTime}
                }).done(function (data) {

                    $(data).each(function (i, item) {
                        unSafeBeh += "<tr ondblclick  = dbClick('"+item.rcrdId+"')><td width='46%' class='al pl10'>" + item.drvSctBhv + "</td><td>" + item.rcrdTime + "</td></tr>";
                    });
                    $("#unSafeBeh").html(unSafeBeh);
                });
                flag=true;
                $(".slide-btn2").click();
            } else {
                $.messager.alert("提示", "请选择开始时间，再进行查询。", "warning");
            }
        } else {
            $.messager.alert("提示", "请选择一辆车，再进行查询。", "warning");
        }
    });



    // -- 界面一加载就加载数据
    initData();

    $(".slide-btn2").click(function(){
        if(flag){
            $(this).addClass("slide-btn2-show");
            $(".fault-box").addClass("fault-box-hide");
        }
        if($(this).hasClass("slide-btn2-show")){
            $(this).removeClass("slide-btn2-show");
            $(".fault-box").removeClass("fault-box-hide");
        }else {
            $(this).addClass("slide-btn2-show");
            $(".fault-box").addClass("fault-box-hide");
        }
        flag=false;
    });

    map = new MapGaoDe(107.49023438, 36.24427318, 8);
    //如果左侧树有选择车辆则直接查询该车辆数据
    //business.execFnByLeftTreeSelectNode('CAR', carAnaCarTrack);
    dbClick = function (rcrdId){
        var rowId = $("#djtable").grid("getDataIDs");
        var rowData;
        for (var i=0 ; i <= rowId.length; i ++) {
            rowData = $("#djtable").jqGrid("getRowData",rowId[i]);
            if(rcrdId==rowData.rcrdId){
                var playIndex = i; // 对应滑块位置数据(0,1,2...)
                $slider.slider("option", "value", playIndex);
                carMove(playIndex);
                flag=true;
                $('#play').click();
            }
        }
    }

    carMove = function (index){   //function carMove(index) {
        if (trackReplay && trackReplay.playIndex != index) {
            trackReplay.setBusIndex(index, true);
        }
    }

});